package com.xhj.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
public class JwtUtil {
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    public static final String SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 生成JwtToken
     * @param id
     * @param nickname
     * @return
     */
    public static String getJwtToken(String id,String nickname){
        return Jwts.builder()
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                .setSubject("xboss-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id",id)
                .claim("nickname",nickname)
                .signWith(SignatureAlgorithm.HS256,SECRET)
                .compact();
    }

    /**
     * 判断JwtToken是否有效
     * @param JwtToken
     * @return
     */
    public static boolean checkToken(String JwtToken){
        if (StringUtils.isEmpty(JwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(JwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断JwtToken是否有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request){
        try {
            String JwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(JwtToken)) return false;
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(JwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员Id
     * @param request
     * @return memberId
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request){
        String JwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(JwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(JwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }
}
